package com.dronff.controller;

import com.dronff.common.ResponseResult;
import com.dronff.common.feign.MallFeign;
import com.dronff.common.feign.OrdersFeign;
import com.dronff.common.feign.UserFeign;
import com.dronff.mapper.MallMapper;
import com.dronff.pojo.Mall;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author tyf
 * @date 2022/7/21 19:11
 */
@RestController
@Slf4j
public class MallController implements MallFeign {
    @Resource
    MallMapper mallMapper;
    @Resource
    UserFeign userFeign;
    @Resource
    OrdersFeign ordersFeign;
    @Override
    public ResponseResult addCommodity(String name, Integer price, Integer count) {
        Mall mall = new Mall(null,name,price,count);
        if(mallMapper.insert(mall)==1){
            return new ResponseResult(200,"添加商品成功，商品id:"+mall.getId());
        }
        return new ResponseResult(500,"添加商品失败");
    }
    @GlobalTransactional
    @Override
    public ResponseResult buy(Integer id, Integer userId) throws Exception {
        Mall mall = mallMapper.selectById(id);
        if(mall==null){
            return new ResponseResult(500,"商品不存在");
        }
        if(mall.getCount()<=0){
            return new ResponseResult(500,"已经没有库存了");
        }
        //减少用户余额
        log.info("开始扣减用户余额");
        ResponseResult dec = userFeign.dec(userId, mall.getPrice());
        log.info("用户余额扣减方法调用完成，返回数据：{}",dec);
        //增加订单
        log.info("开始调用订单接口");
        ResponseResult responseResult = ordersFeign.creOrder(userId, mall.getPrice());
        log.info("订单接口调用完成，返回数据：{}",responseResult);
        Integer integer = mallMapper.decCommodityCount(id, 1);
        if(dec.getCode() != 200||responseResult.getCode()!=200||integer!=1){
            throw new Exception("下单失败");
        }
        return new ResponseResult(200,"下单成功");
    }
}
